const Base = require('./base.js');

module.exports = class extends Base {
	constructor(...arg) {
		super(...arg);
	}
	openAction() {
		let self = this,
			ws = this.websocket,
			data = ws.handshake.query,
			name = data.name,
			room = data.room || ws.id,
			num = 0;
		think.logger.debug('>> websocket: ' + name + ' 链接成功 <<')
		ws.emit('opend',name + ' 连接成功');
		ws.join(room, ()=> {
			//给同房间除自己外的成员发消息
			ws.in(room).emit('message',name + ' 上线');
			let clock = setInterval(function(){
				num++;
				ws.emit('message',(80 + Math.floor(Math.random()*10)),think.datetime(new Date(),'HH:mm:ss'));
				if(num > 100) {
					ws.disconnect();
					clearInterval(clock);
				}
			},5000)
		})
		return this.success();
	}
	messageAction() {
		let data = this.wsData,
			ws = this.websocket;
		think.logger.debug('>> 收到消息： ' + data + ' <<')
		// ws.emit('message','消息-'+data+think.datetime());
		return this.success();
	}

	closeAction() {
		let ws = this.websocket,
			data = ws.handshake.query,
			name = data.name,
			room = data.room || ws.id;
		ws.leave(room,function () {
			//给房间所有成员发消息
			ws.to(room).emit('message',name + '下线');
		})
		think.logger.debug('>> websocket: ' + name + ' 已关闭 <<')
		return this.success();
	}

};
